package cn.portx.view;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf3.dorado.jpa.JpaUtil;
import com.bstek.bdf3.dorado.jpa.policy.SaveContext;
import com.bstek.bdf3.dorado.jpa.policy.impl.SmartSavePolicyAdapter;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.DataResolver;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

import cn.portx.entity.Port;
import cn.portx.entity.Wharf;

@Component
public class PortPR {

	@DataProvider
	@Transactional(readOnly = true)
	public void loadPorts(Page<Port> page, Criteria criteria) {
		JpaUtil.linq(Port.class).where(criteria).paging(page);
	}

	@DataProvider
	@Transactional(readOnly = true)
	public void loadWharfs(Page<Wharf> page, Criteria criteria, String portId) {
		JpaUtil.linq(Wharf.class).equal("portId", portId).where(criteria).paging(page);
	}

	@DataResolver
	@Transactional
	public void savePorts(List<Port> list) {
		JpaUtil.save(list, new SmartSavePolicyAdapter() {

			@Override
			public boolean beforeInsert(SaveContext context) {
				Object parent = context.getParent();
				Object entity = context.getEntity();
				if (parent instanceof Port && entity instanceof Wharf) {
					((Wharf) entity).setPortId(((Port) parent).getId());
				}
				return true;
			}

		});
	}

	@Expose
	@Transactional
	public void deletePort(String id) {
		JpaUtil.lind(Wharf.class).equal("portId", id).delete();
		JpaUtil.lind(Port.class).idEqual(id).delete();
	}

	@Expose
	@Transactional
	public void deleteWharf(String id) {
		JpaUtil.lind(Wharf.class).idEqual(id).delete();
	}
}
